package com.example.common.utils;

import com.alibaba.fastjson.JSON;
import com.example.common.entity.AccessTokenBody;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

/**
 * AccessToken工具类
 * @author sunyong
 * @date 2021/8/25
 */
@Slf4j
public class AccessTokenUtils {
    /**
     * 解密token
     * @param encryptToken
     * @return
     */
    private static final String TOKEN_KEY_PREFIX = "openapi:access_token:";

    public static AccessTokenBody decrypt(String encryptToken){
        String decryptedTokenBody = null;
        try {
            decryptedTokenBody = WillingAESUtils.decrypt(encryptToken);
        } catch (Exception e) {
            log.error("AccessTokenUtils.decrypt 失败，encryptToken = {}", encryptToken);
        }
        AccessTokenBody tokenBody = null;
        try {
            tokenBody = JSON.parseObject(decryptedTokenBody, AccessTokenBody.class);
        } catch (Exception e) {
            log.error("AccessTokenUtils.decrypt parseObject 失败，decryptedTokenBody = {}", decryptedTokenBody);
        }
        return tokenBody;
    }

    @SneakyThrows
    public static String encrypt(AccessTokenBody tokenBody) {
        if (tokenBody == null){
            return null;
        }
        String jsonStr = JSON.toJSONString(tokenBody);
        return WillingAESUtils.encrypt(jsonStr);
    }

    public static String getTokenKey(String appId){
        return TOKEN_KEY_PREFIX + appId;
    }

}
